package top.xiaoqy.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域工具类
 * 不太会写
 *
 * @Author: 小清远
 * @Time: 2023/9/30 22:09
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //接受任意域名的请求
        config.addAllowedOrigin("*");
        //不支持提交COOKIE数据
        config.setAllowCredentials(false);
        //绑定请求头信息，使用通配符
        config.addAllowedHeader("*");
        //支持任意提交方法
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource configSource
                = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**",config);
        return new CorsFilter(configSource);
    }

    /*@Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        //接受任意域名的请求
        config.addAllowedOrigin("*");
        //不支持提交COOKIE数据
        config.setAllowCredentials(false);
        //绑定请求头信息，使用通配符
        config.addAllowedHeader("*");
        //支持任意提交方法
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**",config);
        return new CorsFilter(configSource);
    }

     @Bean
    public CorsFilter corsFilter() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOriginPattern("*");//2.4.0后的写法
       // config.addAllowedOrigin("*");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
    */
}